package com.platform.netty.udp;

import com.platform.netty.udp.initializer.UdpServerInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * UDP服务端
 */
@Slf4j
@Component
@Order(value = 2)
public class UdpServer implements CommandLineRunner {

    //boss事件轮询线程组
    //处理Accept连接事件的线程，这里线程数设置为1即可，netty处理链接事件默认为单线程，过度设置反而浪费cpu资源
    private EventLoopGroup boss = new NioEventLoopGroup(1);

    @Autowired
    private UdpServerInitializer udpServerInitializer;

    //与客户端建立连接后得到的通道对象
    private Channel channel;

    /**
     * 开启Netty udp server服务
     *
     * @return
     */
    public ChannelFuture start(int port) throws Exception {
        //启动类
        Bootstrap bootstrap = new Bootstrap();
        //组配置，初始化ServerBootstrap的线程组
        bootstrap.group(boss)
                ///由于我们用的是UDP协议，所以要用NioDatagramChannel来创建
                .channel(NioDatagramChannel.class)
                //支持广播
                .option(ChannelOption.SO_BROADCAST, true)
                //业务处理类
                .handler(udpServerInitializer);
        //Future：异步任务的生命周期，可用来获取任务结果
        //绑定端口，开启监听，同步等待
        ChannelFuture channelFuture = bootstrap.bind(port).syncUninterruptibly();
        if (channelFuture != null && channelFuture.isSuccess()) {
            log.info("UDP服务器启动成功, port = {}", port);
            //获取通道
            channel = channelFuture.channel().closeFuture().sync().channel();//获取通道
        } else {
            log.error("UDP服务器启动失败");
        }
        return channelFuture;
    }

    /**
     * 停止Netty udp server服务
     */
    @PreDestroy
    public void destroy() {
        if (channel != null) {
            channel.close();
        }
        try {
            Future<?> future = boss.shutdownGracefully().await();
            if (!future.isSuccess()) {
                log.error("netty udp bossGroup shutdown fail, {}", future.cause());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("UDP服务器关闭");
    }

    @Override
    @Async
    public void run(String... args) throws Exception {
        this.start(9999);
    }
}
